package com.itheima.question.timer;

import com.github.tobato.fastdfs.exception.FdfsServerException;
import com.itheima.common.contants.RedisPicConstants;
import com.itheima.question.config.FastDFSClientUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.Set;

@Component
@Slf4j
public class ClearPicTask {
    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private FastDFSClientUtil fastDFSClientUtil;

    @Scheduled(cron = "0/5 12 * 1 * ?")
    public void clearPic(){
        Set<String> pics=redisTemplate.opsForSet().difference(RedisPicConstants.ALL_PIC,RedisPicConstants.USE_PIC);
        log.info("定时任务开始执行，需要清理的图片有"+pics);
        for (String pic:pics){
            log.info(pic);
            try {
                fastDFSClientUtil.delFile(pic);
            }
            catch (FdfsServerException e){
                int errorCode = e.getErrorCode();
                if (errorCode==2){
                    for (String picc:pics
                    ) {//清理多余redis set值
                        redisTemplate.opsForSet().remove(RedisPicConstants.ALL_PIC,pic);
                    }
                }
            }

        }

    }
}

